package org.rui.rpc.protocol;

/**
 * @author: linweirui
 * @date: 2024/12/09 10:28
 */

import io.vertx.core.buffer.Buffer;
import org.rui.rpc.constant.ProtocolConstant;
import org.rui.rpc.enums.ProtocolMessageSerializerEnum;
import org.rui.rpc.enums.ProtocolMessageTypeEnum;
import org.rui.rpc.model.RpcRequest;
import org.rui.rpc.model.RpcResponse;
import org.rui.rpc.serializer.Serializer;
import org.rui.rpc.serializer.SerializerFactory;

import java.io.IOException;

/**
 * 协议消息解码器
 */
public class ProtocolMessageDecoder {
    public static ProtocolMessage<?> decode(Buffer buffer) throws IOException {
        //分别从指定位置读取buffer
        ProtocolMessage.Header header = new ProtocolMessage.Header();
        byte magic = buffer.getByte(0);
        if(magic != ProtocolConstant.PROTOCOL_MAGIC){
            throw new RuntimeException("消息magic非法");
        }
        header.setMagic(magic);
        header.setVersion(buffer.getByte(1));
        header.setSerializer(buffer.getByte(2));
        header.setType(buffer.getByte(3));
        header.setStatus(buffer.getByte(4));
        header.setRequestId(buffer.getLong(5));
        header.setBodyLength(buffer.getInt(13));
        //解决粘包问题，只读取指定长度的数据
        byte[] bodyBytes = buffer.getBytes(17, 17 + header.getBodyLength());
        //解析消息体
        //解析序列化器类型
        ProtocolMessageSerializerEnum serializerEnum = ProtocolMessageSerializerEnum.getMessageSerializerByValue(buffer.getByte(2));
        if(serializerEnum ==null){
            throw new RuntimeException("序列化消息协议不存在");
        }
        Serializer serializer = SerializerFactory.getSerializer(serializerEnum.getText());
        //解析请求类型
        ProtocolMessageTypeEnum messageTypeEnum = ProtocolMessageTypeEnum.getMessageTypeByValue(header.getType());
        //根据请求类型处理不同的请求
        switch (messageTypeEnum) {
            case REQUEST:
                RpcRequest request = serializer.deserialize(bodyBytes, RpcRequest.class);
                return new ProtocolMessage<>(header, request);
            case RESPONSE:
                RpcResponse response = serializer.deserialize(bodyBytes, RpcResponse.class);
                return new ProtocolMessage<>(header, response);
            case HEART_BEAT:
            case OTHERS:
            default:
                throw new RuntimeException("暂不支持该消息类型");
        }
    }
}
